<template>
  <div class="chat-container">
    <div class="message-list" ref="messageListRef" @scroll="handleScroll">
      <div v-if="loading" class="loading-more">
        <el-icon class="loading-icon"><loading /></el-icon>
        <span>加载更多消息...</span>
      </div>
      <div
        v-for="item in messageList"
        :key="item._id"
        class="message-item"
        :class="{ 'message-mine': item.msg.from == suid }"
      >
        <div class="avatar">
          <el-avatar :size="40" :src="item.msg.fromAvatar">
            <template #error>
              <img
                src="@/assets/app-mj.png"
                alt="avatar"
                style="width: 40px; height: 40px; border-radius: 50%"
              />
            </template>
          </el-avatar>
        </div>
        <div class="message-content">
          <div class="message-info">
            <span class="name">{{ sendUserName(item.msg) }}</span>
          </div>
          <!-- 文本消息 -->
          <div v-if="item.msg.contentType === 1" class="message-text">
            {{ item.msg.content }}
          </div>
          <!-- 图片消息 -->
          <div v-else-if="item.msg.contentType === 2" class="message-image">
            <el-image
              :src="item.msg.content"
              :preview-src-list="[item.msg.content]"
              fit="cover"
              :initial-index="0"
              preview-teleported
            >
              <template #error>
                <div class="image-error">
                  <el-icon><picture-filled /></el-icon>
                </div>
              </template>
            </el-image>
            <div v-if="item.msg.exData?.fileName" class="file-info">
              <span>{{ item.msg.exData.fileName }}</span>
              <span>{{ formatFileSize(item.msg.exData.fileSize) }}</span>
            </div>
          </div>
          <!-- 表情消息 -->
          <div v-else-if="item.msg.contentType === 3" class="message-emoji">
            <el-image
              :src="item.msg.content"
              style="width: 100px; height: 100px"
              fit="contain"
            />
          </div>
          <!-- 发送的服务消息 -->
          <div v-else-if="item.msg.contentType === 8" class="message-goods-card" @click="openPage(item)">
            <div class="goods-card">
              <el-image
                class="goods-cover"
                :src="item.msg.exData.coverPic"
                fit="cover"
                style="width: 80px; height: 80px; border-radius: 8px; background: #f5f5f5"
              />
              <div class="goods-info">
                <p class="msg-type">分享服务</p>
                <div class="goods-name">{{ item.msg.exData.goodsName }}</div>
                <div class="goods-type">{{ item.msg.exData.typeName }}</div>
                <div class="goods-price">￥{{ item.msg.exData.goodsAmount }}</div>
              </div>
            </div>
          </div>
          <!-- 邀请支付消息 -->
          <div v-else-if="item.msg.contentType === 10" class="message-order-card" @click="openPage(item)">
            <div class="order-card">
              <el-image
                class="order-cover"
                :src="item.msg.exData.goodsDetails.coverPic"
                fit="cover"
                style="width: 80px; height: 80px; border-radius: 8px; background: #f5f5f5"
              />
              <div class="order-info">
                <p class="msg-type">邀请支付</p>
                <div class="order-goods-name">{{ item.msg.exData.goodsDetails.goodsName }}</div>
                <div class="order-desc">
                  {{ item.msg.exData.goodsDetails.standard?.introduce || item.msg.exData.goodsDetails.versionInfo?.introduce || '无描述' }}
                </div>
                <div class="order-meta">
                  <span class="order-buyer">买家：{{ item.msg.exData.orderDetails.nickName }}</span>
                  <span class="order-amount">￥{{ item.msg.exData.orderDetails.amount }}</span>
                </div>
              </div>
            </div>
          </div>
          <div class="message-time">{{ formatTime(item.msg.time) }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from "vue";
import { getMessageList } from "@/api/message";
import { PictureFilled, Loading } from "@element-plus/icons-vue";

const props = defineProps({
  chat: {
    type: Object,
    required: true,
    default: () => ({
      from: "",
      to: "",
    }),
  },
  currentUserId:{
    type: String,
    default: ''
  }
});

const suid = ref("");
onMounted(() => {
  const serviceInfo = localStorage.getItem("imUserInfo");
  suid.value = props.currentUserId;
});

const messageList = ref([]);
const page = ref(1);
const pageSize = ref(20);
const loading = ref(false);
const hasMore = ref(true);
const messageListRef = ref(null);
const initialLoad = ref(true);

const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  return date
    .toLocaleString("zh-CN", {
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      hour12: false,
    })
    .replace(/\//g, "-");
};

const sendUserName = (msgItem)=>{
    const userType = msgItem.fromType
    if(userType === 3){
      return '客服:' + msgItem.fromName
    }
    return msgItem.fromName
}

const formatFileSize = (size) => {
  if (!size) return "";
  if (size < 1024) return size + "B";
  if (size < 1024 * 1024) return (size / 1024).toFixed(2) + "KB";
  return (size / (1024 * 1024)).toFixed(2) + "MB";
};

const getMsgs = async (isFirstLoad = false) => {
  if (!isFirstLoad && (loading.value || !hasMore.value)) return;
  loading.value = true;

  try {
    const params = {
      user: props.chat.from,
      toUser: props.chat.to,
      page: page.value,
      pageSize: pageSize.value,
    };

    // 记录当前滚动位置和高度
    const oldScrollHeight = messageListRef.value?.scrollHeight || 0;
    const oldScrollTop = messageListRef.value?.scrollTop || 0;

    const res = await getMessageList(params);
    // 按时间倒序排列，新消息在前，旧消息在后
    const sortedList = res.list.reverse();

    if (isFirstLoad) {
      messageList.value = sortedList;
      hasMore.value = res.totalPages > 1;
      initialLoad.value = false;
      nextTick(() => {
        scrollToBottom();
      });
    } else {
      // 加载更多时，新消息添加到前面
      messageList.value = [...sortedList, ...messageList.value];
      hasMore.value = page.value < res.totalPages;

      // 保持滚动位置
      nextTick(() => {
        if (messageListRef.value) {
          const newScrollHeight = messageListRef.value.scrollHeight;
          // 新内容的高度差
          const heightDiff = newScrollHeight - oldScrollHeight;
          // 设置新的滚动位置 = 原位置 + 新增内容的高度
          messageListRef.value.scrollTop = oldScrollTop + heightDiff;
        }
      });
    }
  } catch (error) {
    console.error("获取消息列表失败:", error);
  } finally {
    loading.value = false;
  }
};

const scrollToBottom = () => {
  if (messageListRef.value) {
    messageListRef.value.scrollTop = messageListRef.value.scrollHeight;
  }
};

const handleScroll = (e) => {
  if (initialLoad.value || loading.value) return;

  const { scrollTop } = e.target;

  // 滚动到顶部时加载更多（距离顶部30px以内）
  if (scrollTop < 30 && hasMore.value) {
    page.value++;
    getMsgs();
  }
};

watch(
  () => props.chat,
  () => {
    messageList.value = [];
    page.value = 1;
    hasMore.value = true;
    initialLoad.value = true;
    getMsgs(true);
  },
  { deep: true }
);

onMounted(() => {
  getMsgs(true);
});

const openPage = (item)=>{
  window.open(`http://jinenghouzi.com/details?id=${item.msg.exData.id || item.msg.exData.goodsDetails.id}`)
}
</script>

<style scoped>
.chat-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  position: relative;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
  width: 100%;
}

.message-mine {
  flex-direction: row-reverse;
}

.avatar {
  margin: 0 10px;
  flex-shrink: 0;
}

.message-content {
  max-width: 70%;
  display: flex;
  flex-direction: column;
}

.message-mine .message-content {
  align-items: flex-end;
}

.message-info {
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.message-mine .message-info {
  flex-direction: row-reverse;
}

.name {
  font-size: 12px;
  color: #999;
}

.time {
  font-size: 12px;
  color: #999;
}

.message-text {
  background: #f0f2f5;
  padding: 10px 15px;
  border-radius: 16px;
  word-break: break-all;
  position: relative;
  margin: 0;
  font-size: 14px;
  line-height: 1.4;
}

.message-mine .message-text {
  background: #95ec69;
}

.message-image {
  max-width: 300px;
  border-radius: 12px;
  overflow: hidden;
  margin: 0;
}

.message-image .el-image {
  width: 100%;
  border-radius: 12px;
  display: block;
}

.image-error {
  width: 100%;
  height: 200px;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 24px;
  border-radius: 12px;
}

.file-info {
  font-size: 12px;
  color: #666;
  padding: 5px 8px;
  display: flex;
  justify-content: space-between;
  background: rgba(0, 0, 0, 0.03);
  border-radius: 0 0 12px 12px;
  margin-top: -4px;
}

.message-emoji {
  background: transparent;
  padding: 5px;
  margin: 0;
  border-radius: 12px;
  overflow: hidden;
}

.loading-more {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 0;
  color: #909399;
  font-size: 14px;
  background: rgba(255, 255, 255, 0.9);
  z-index: 1;
}

.loading-icon {
  animation: rotating 2s linear infinite;
  margin-right: 6px;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  padding: 0 4px;
}

.message-info {
  margin-bottom: 5px;
  display: flex;
  align-items: center;
}

.message-mine .message-time {
  text-align: right;
}
/* 卡片消息 */
.message-goods-card {
  margin: 8px 0;
  display: flex;
  align-items: flex-start;
}

.goods-card {
  display: flex;
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
  padding: 10px;
  min-width: 260px;
  max-width: 320px;
  gap: 12px;
}

.goods-cover {
  flex-shrink: 0;
}

.goods-info {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-width: 0;
}

.goods-name {
  font-size: 15px;
  font-weight: 600;
  color: #222;
  margin-bottom: 6px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.goods-type {
  font-size: 12px;
  color: #888;
  margin-bottom: 8px;
}

.goods-price {
  font-size: 16px;
  color: #ff4d4f;
  font-weight: bold;
}
/* 邀请支付 */
/* 邀请支付卡片消息 */
.message-order-card {
  margin: 8px 0;
  display: flex;
  align-items: flex-start;
}

.order-card {
  display: flex;
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
  padding: 10px;
  min-width: 260px;
  max-width: 360px;
  gap: 12px;
  cursor: pointer;
}

.order-cover {
  flex-shrink: 0;
}

.order-info {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-width: 0;
  flex: 1;
}

.msg-type{
  font-size: 14px;
  color: #999;
}

.order-goods-name {
  font-size: 15px;
  font-weight: 600;
  color: #222;
  margin-bottom: 4px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.order-desc {
  font-size: 12px;
  color: #888;
  margin-bottom: 8px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.order-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
  margin-bottom: 6px;
}

.order-buyer {
  color: #666;
}

.order-amount {
  color: #ff4d4f;
  font-weight: bold;
}

.pay-btn {
  align-self: flex-end;
  margin-top: 2px;
}
</style>
